package shop.controller.common;


import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import shop.core.common.bean.JSONResult;
import shop.core.plugins.ueditor.ActionEnter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import shop.core.util.StrUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Random;

/**
 * Ueditor文件上传类
 */
@Controller
@RequestMapping("/manage/ued")
public class UEditorController {
    protected static final Logger logger = LoggerFactory.getLogger(UEditorController.class);

    @RequestMapping(value="/config")
    public void config(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
            String exec = new ActionEnter(request, rootPath).exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            logger.error(""+e);
        }
    }

    /**
     * 上传文件
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    @ResponseBody
    private JSONResult uploadFile(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws IOException {
        JSONResult jsonResult= new JSONResult();
        String path=request.getSession().getServletContext().getRealPath("/ueditor/upload/file/");//文件上传服务器地址
        logger.debug("文件上传路径："+path);
        String fileName=file.getOriginalFilename();//获取上传文件名
        String suffix = fileName.substring(fileName.lastIndexOf("."));//获取文件后缀名
        if(!StringUtils.isBlank(request.getParameter("fileName")))
            fileName=request.getParameter("fileName")+suffix;
        File targetFile=new File(path,fileName);//创建文件夹存储文件
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        file.transferTo(targetFile);
        String newPath = "ueditor/upload/file/"+ fileName;//服务器返回地址
        jsonResult.setData(newPath);
        return jsonResult;
    }
}